package com.itheima.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.itheima.dtos.ArticleDto;
import com.itheima.dtos.ArticleHomeDto;
import com.itheima.mapper.ApArticleConfigMapper;
import com.itheima.mapper.ApArticleContentMapper;
import com.itheima.mapper.ApAuthorMapper;
import com.itheima.pojos.ApArticle;
import com.itheima.mapper.ArticleMapper;
import com.itheima.pojos.ApArticleConfig;
import com.itheima.pojos.ApArticleContent;
import com.itheima.pojos.ApAuthor;
import com.itheima.service.ArticleService;
import com.itheima.vos.ArticleVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

/**
 * @author wangjiexin
 */
@Service
public class ArticleServiceImpl implements ArticleService {

    @Autowired
    private ArticleMapper articleMapper;
    @Autowired
    private ApAuthorMapper apAuthorMapper;
    @Autowired
    private ApArticleContentMapper apArticleContentMapper;

    @Autowired
    private ApArticleConfigMapper apArticleConfigMapper;

    @Override
    public List<ArticleVO> load(ArticleHomeDto dto) {
        //1.加载首页
        //前端会在minBehotTime 传2063的时间

        //publish_time<minBehotTime and 上架状态

        return articleMapper.loadArticle(dto);
    }

    @Override
    public List<ArticleVO> loadmore(ArticleHomeDto dto) {
        // 3.上拉加载
        //前端会在minBehotTime传当前列表中，最底下那篇文章的发布时间
        //publish_time<minBehotTime and 上架状态

        return articleMapper.loadArticle(dto);
    }

    @Override
    public List<ArticleVO> loadnew(ArticleHomeDto dto) {
        // 2．下拉刷新
        //前端会在MaxBehotTime传当前列表中最顶上那片文章的发布时间
        //publish_time>minBehotTime and 上架状态

        return articleMapper.loadArticle(dto);
    }

    @Override
    public ApArticle saveArticle(ArticleDto dto) {

        //入参判断
        if (dto==null){
            throw  new RuntimeException("入参不能为空~！");
        }
        //获取dto中的id，根据id判断是修改还是新增
        Long id = dto.getId();

        //将dto数据转换成我们需要的结构
        ApArticle article=new ApArticle();
        BeanUtils.copyProperties(dto,article);

        //补充dto没有传值进来的字段
        article.setFlag((byte) 0);
        article.setLikes(0);
        article.setCollection(0);
        article.setComment(0);
        article.setViews(0);

        article.setCreatedTime(new Date());
        article.setSyncStatus(true);
        article.setOrigin(true);

        //通过作者id，查询mapper得到作者的名字
        ApAuthor apAuthor=apAuthorMapper.selectById(dto.getAuthorId());
        if (apAuthor==null){
            //如果查不到这个作者，那么就给它赋个名字
            article.setAuthorName(apAuthor.getName());
        }

        //新增
        if (id==null){
            //ap_article
            int articlevResult = articleMapper.insert(article);
                if (articlevResult!=1){
                    throw new RuntimeException("新增文章失败");
                }
            //ap_article_config
            //配置数据组装
            ApArticleConfig apArticleConfig=new ApArticleConfig();
            //文章id
            apArticleConfig.setArticleId(article.getId());
            //是否可以评论
            apArticleConfig.setIsComment(true);
            //是否删除，新增不可能删除
            apArticleConfig.setIsDelete(false);
            //是否下架，新增不可能下架
            apArticleConfig.setIsDown(false);
            //是否可以分享
            apArticleConfig.setIsForward(true);
            int configResult = apArticleConfigMapper.insert(apArticleConfig);
            if (configResult!=1){
                throw new RuntimeException("新增文章配置失败");
            }
            //ap_article_content
            ApArticleContent content=new ApArticleContent();
            //文章内容
            content.setContent(dto.getContent());
            //文章id
            content.setArticleId(article.getId());
            int contentResult = apArticleContentMapper.insert(content);
            if (contentResult!=1){
                throw new RuntimeException("新增文章内容失败");
            }

        }
        //修改（事务）
        else {
            //修改之前查询文章是否存在
            ApArticle res = articleMapper.selectById(id);
            if (res==null){
                throw new RuntimeException("文章"+id+"不存在");
            }
            //ap_article
            //将传进来的dto覆盖上去
            BeanUtils.copyProperties(dto,article);
            //然后进行修改
            int updateArticle = articleMapper.updateById(article);
            if (updateArticle!=1){
                throw new RuntimeException("修改文章失败");
            }
            //ap_article_config 这个不需要，因为这个改不了

            //ap_article_content
           // LambdaQueryWrapper<ApArticleContent> wrapper=new LambdaQueryWrapper<>();
            //换另一种蓝不大方法
            QueryWrapper<ApArticleContent> wrapper=new QueryWrapper<>();
            wrapper.eq("article_id",id);
            //查询一下文章内容
            ApArticleContent apArticleContent = apArticleContentMapper.selectOne(wrapper);
            if (apArticleContent==null){
                throw new RuntimeException("文章内容不存在");
            }

            //把传进来的文章内容 写进去
            apArticleContent.setContent(dto.getContent());
            int resContent = apArticleContentMapper.updateById(apArticleContent);
            if (resContent!=1){
                throw new RuntimeException("修改文章内容失败~！");
            }
        }
        //以防万一，这边做一个回写，保证前后id不会漏掉
        article.setId(id);
        //把作者信息 id返回回去
        return article;
    }
}
